<template>
  <Dialog v-model="dialogVisible" title="添加房产维度组合">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
      @keydown.enter.prevent="submitForm"
    >
    <el-form-item
    v-for="(property, index) in propertyList"
    :key="index"
    :label="property.name"
    :prop="'properties.' + index + '.values[0].id'"
  >
    <el-select
      v-model="formData.properties[index].values[0].name"
      :reserve-keyword="false"
      allow-create
      class="!w-360px"
      default-first-option
      filterable
      :placeholder="`请选择${property.name}`"
      @change="(value) => handleSelectChange(value, index)"
    >
      <el-option
        v-for="item in property.values"
        :key="item.id"
        :label="item.name"
        :value="item.name"
      />
    </el-select>
  </el-form-item>
    </el-form>

    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { defineProps, PropType, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useMessage } from '@/hooks/web/useMessage'

defineOptions({ name: 'HousePropertyComposeForm' })

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()
const emit = defineEmits(['success'])

// 接收的属性列表类型定义
interface PropertyItem {
  values: any
  name: string
}
const props = defineProps({
  propertyList: {
    type: Array as PropType<PropertyItem[]>,
    required: true
  }
})

// 初始化 formData
const formData = ref<{
  properties: { 
    id: number | null; 
    name: string | null;
    values: [{
      id: number | null; 
      name: string 
    }]
  }[]
}>({
  properties: []
})

/** 初始化表单数据 */
const initFormData = () => {
  formData.value.properties = props.propertyList.map(property => ({
    id: property.id,
    name: property.name,
    values: [{
      id: null,
      name: ''
    }]
  }))
}

const handleSelectChange = (value: string, index: number) => {
  const selectedItem = props.propertyList[index].values.find(
    (item: { name: string; id: number }) => item.name === value
  )
  if (selectedItem) {
    formData.value.properties[index].values[0].id = selectedItem.id
  }
}

const formRules = computed(() => {
  const rules: Record<string, any> = {}
  props.propertyList.forEach((_, index) => {
    rules[`properties.${index}.values[0].id`] = [
      { required: true, message: '该项不能为空', trigger: 'change' }
    ]
  })
  return rules
})

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  resetForm()
}
defineExpose({ open })

/** 提交表单 */
const submitForm = async () => {
  // 1.2 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return

  // 2.2 提交请求
  formLoading.value = true
  try {
    const data = formData.value.properties as any
    message.success(t('common.createSuccess'))
    dialogVisible.value = false
    emit('success', data) // 传递表单数据
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  initFormData()
  formRef.value?.resetFields()
}

</script>